package com.gate.ws.spring.listener;

import com.gate.ws.spring.network.NettyServerImpl;
import com.gate.ws.spring.network.NetworkService;
import com.gate.ws.spring.process.upmsg.PackageProcessFactory;
import com.gate.ws.spring.request.RpcConfig;
import com.gate.ws.spring.service.MqSender;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author lbc
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NettyListener implements ApplicationListener<ContextRefreshedEvent> {

    private final MqSender mqSender;

    @Value("${nami.mqTags}")
    private String mqTags;

    @Value("${dubbo.protocol.port}")
    private int dubboPort;

    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            try {
                RpcConfig rpcConfig = new RpcConfig();
                rpcConfig.setMqTags(mqTags);
                rpcConfig.setDubboPort(dubboPort);

                PackageProcessFactory processFactory = new PackageProcessFactory(mqSender, rpcConfig);
                processFactory.init();

                NetworkService networkService = new NettyServerImpl(processFactory);
                networkService.start();
//                Runtime.getRuntime().addShutdownHook(new Thread() {
//                    public void run() {
//                        try {
//                            imServer.stop();
//                        } catch (Exception e) {
//                            throw new RuntimeException(e);
//                        }
//                    }});

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
        }
    }

    /**
     * bean已注销，调用会失败
     *
     * @throws Exception
     */
//    @PreDestroy
//    public void stop() throws Exception {
//        this.imServer.stop();
//    }


}
